package com.cc.visitor.controller;

import com.cc.visitor.utils.WechatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author chanchaw
 * @create 2025-01-11 15:53
 */
@CrossOrigin
@RestController
@RequestMapping("/wxmini")
public class WxminiController {
    private static final Logger logger = LoggerFactory.getLogger("wxmp");

    /**
     * 用于验证是否微信服务器发送来的消息（小程序中验证微信服务器）
     * 类似：wxmp/mp （服务号中验证微信服务器）
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/revice")
    public String checkSignature(HttpServletRequest request, HttpServletResponse response){
        String signature = request.getParameter("signature");
        String nonce = request.getParameter("nonce");
        String timestamp = request.getParameter("timestamp");
        String echostr = request.getParameter("echostr");

        String tip = "signature = " + signature + ",nonce = " + nonce + ", timestamp = " + timestamp + ", echostr = " + echostr;
        logger.info(tip,"微信服务器get请求验证本后台服务的合法性");

        if(WechatUtils.checkServerMini(timestamp,nonce,signature)){
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.print(echostr);
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            logger.info("小程序后台验证微信服务器身份成功");
        }else{
            logger.info("小程序后台验证微信服务器身份失败");
        }
        return null;
    }
}
